package com.yaorange.web;

import com.yaorange.entity.Notice;
import com.yaorange.service.NoticeService;
import com.yaorange.vo.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/personnel/announcement")
@CrossOrigin
public class NoticeController {

    @Resource
    //spring提供的发送消息模板
    //官方API：https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/messaging/simp/SimpMessagingTemplate.html
    private SimpMessagingTemplate simpMessagingTemplate;

    @Autowired
    private NoticeService noticeService;

    //基于Spring提供操作消息发送的模板类，给订阅了指定地址的客户端发送消息
    @GetMapping("/sendMsgByAll/{msg}")
    @ResponseBody
    public Object sendMsgByAll(@PathVariable("msg") String msg) {
        //给订阅了/topic的客户端发送信息
        simpMessagingTemplate.convertAndSend("/topic", new ResponseMessage("您有一条新的公告，请注意查收哦！！！标题：" +msg));
        return "success";
    }


    //查询
    @GetMapping("/notice")
    public List<Notice> noticeList(){
        return noticeService.getList();
    }


    //回显到编辑的弹窗里
    @GetMapping("/{noticeId}")
    public Notice getNotice(@PathVariable Integer noticeId){
        return  noticeService.findNotice(noticeId);
    }


    //增
    @PostMapping
    public Map<String,Object> add(@RequestBody Notice notice){
        Map<String, Object> map = new HashMap<>();
        notice.setNoticeCreatedTime(new Date());
        notice.setNoticePublishTime(new Date());
        int rows=noticeService.add(notice);
        if(rows > 0){
            map.put("status",20000);
            map.put("msg","公告发布成功");
        }else{
            map.put("msg","公告发布失败");
        }
        return map;
    }


    //删
    @DeleteMapping("/{noticeId}")
    public Map<String,Object> delete(@PathVariable Integer noticeId){
        Map<String, Object> map = new HashMap<>();

        int rows = noticeService.delete(noticeId);
        if(rows > 0){
            map.put("status",20000);
            map.put("msg","公告删除成功");
        }else{
            map.put("msg","公告删除失败");
        }
        return map;
    }


    //改
    @PutMapping
    public Map<String,Object> putNotice(@RequestBody Notice notice){
        Map<String, Object> map = new HashMap<>();
        //设置跟踪字段数据
        //TODO:设置操作员工
        notice.setNoticeUpdatedTime(new Date());//设置修改日期
        int rows = noticeService.updateNotice(notice);
        if(rows > 0){
            map.put("status",20000);
            map.put("msg","公告修改成功");
        }else{
            map.put("msg","公告修改失败");
        }
        return map;
    }

}
